<template>
  <div>
    <div class="g6 mb20">
      <span>提示：事件方法会在第一个参数中内置context上下文</span>
    </div>
    <div class="ks-row-middle mb20 lh1">
      <div class="mr10">参数</div>
      <i
        class="el-icon-circle-plus-outline iconcolor f20 poi"
        @click="addEventParam"
      ></i>
    </div>

    <div
      class=" pr15 ell item"
      v-for="(param, index) in paramList"
      :key="index"
    >
      <div
        :key="index"
        style="min-height: 32px"
        class="ks-row-middle-between mb10">
        <span class="ell">{{ param.value }}</span>
        <span v-if="tableFlag? index > 2 : index > 0" class="g6">
          <el-button
            type="text"
            style="margin-right: 10px"
            @click="editEventParam(param.value, index)">
            <i class="el-icon-edit"></i>
          </el-button>
          <span
            class="iconfont iconicon_shanchu poi"
            @click="removeParams(param, index)"
          ></span>
        </span>

      </div>
    </div>
    <div>
    </div>
    <addParam ref="addParam" @addParam="handleAddParam" @editParam="handleEditParam"/>
  </div>
</template>

<script>
import Blockly from 'blockly'
import addParam from '../addParam'
export default {
  name: 'RootFunctionExpression',
  props: {
    eventItem: {}, // 需要逻辑编排的对象
    componentItem: {},
    block: {},
    workspace: {}
  },
  components: { addParam },
  data () {
    return {
      tableFlag: false,
      titleLabel: '全局配置', // 标题
      formData: {},
      paramList: []
    }
  },
  watch: {
    'block': {
      handler () {
        this.getBlockData()
      },
      immediate: true
    }
  },
  methods: {
    getBlockData () {
      const composeKey = this.block?.composeKey || ''
      if (composeKey.startsWith('tb_o_click')) {
        this.tableFlag = true
      } else {
        this.tableFlag = false
      }
      const rootBlock = this?.workspace?.getBlockById(this.block.id)
      this.paramList = []
      for (let i = 0; i < rootBlock.itemCount_; i++) {
        const input = rootBlock.getInput(`ADD${i}`)
        if (i === 0 || (this.tableFlag && i <= 2)) {
          const insideBlock = rootBlock.getInputTargetBlock(`ADD${i}`)
          if (!insideBlock) return
          insideBlock.setEditable(false)
          insideBlock.setDeletable(false)
          insideBlock.setMovable(false)
        }
        const value = input?.connection?.targetConnection?.sourceBlock_?.getFieldValue('CODE') || ''
        this.paramList.push({ value })
      }
    },
    // 添加事件参数
    addEventParam () {
      this.$refs.addParam.addForm({}, this.paramList.length)
    },
    editEventParam (param, index) {
      this.$refs.addParam.editForm({ param }, index)
    },
    handleAddParam (data) {
      this.paramList.push({ value: data.param })
      const index = data.index || 0
      const rootBlock = this?.workspace?.getBlockById(this.block.id) // input
      rootBlock.itemCount_++
      rootBlock.updateShape_()
      var connection = rootBlock.getInput(`ADD${index}`).connection
      const newBlock = this.workspace.newBlock('params_input')
      newBlock.setFieldValue(data.param, 'CODE')
      connection.connect(newBlock.outputConnection)
      // rootBlock.initSvg()
      // rootBlock.updateShape_()
      this.updateWorkspaceWithXml()
    },
    handleEditParam (data) {
      const rootBlock = this?.workspace?.getBlockById(this.block.id)
      this.$set(this.paramList, data.index, { value: data.param })
      const index = data.index || 0
      const targetBlock = rootBlock.getInputTargetBlock(`ADD${index}`)
      // 如果积木被移除就没有targetBlock 需要手动加一个，有的话直接修改值
      if (!targetBlock) {
        const connection = rootBlock.getInput(`ADD${index}`).connection
        const newBlock = this.workspace.newBlock('params_input')
        newBlock.setFieldValue(data.param, 'CODE')
        connection.connect(newBlock.outputConnection)
        this.updateWorkspaceWithXml()
      } else {
        targetBlock.setFieldValue(data.param, 'CODE')
      }
    },

    // 移除参数
    removeParams (param, index) {
      this.paramList.splice(index, 1)
      const rootBlock = this?.workspace?.getBlockById(this.block.id)
      // // 移除input并将 对应input中的积木从workspace删除
      const insideContent = rootBlock.getInputTargetBlock(`ADD${index}`)
      insideContent && insideContent.dispose()
      rootBlock.removeInput(`ADD${index}`)

      const targetInsideBlocks = [] // 保存之前的连接块
      for (let i = index + 1; i < rootBlock.itemCount_; i++) {
        const targetBlock = rootBlock.getInputTargetBlock(`ADD${i}`)
        targetInsideBlocks.push(targetBlock)
        rootBlock.removeInput(`ADD${i}`)
      }
      rootBlock.itemCount_--
      rootBlock.updateShape_()
      for (let i = 0; i < targetInsideBlocks.length; i++) {
        var connection = rootBlock.getInput(`ADD${index + i }`).connection
        const targetBlock = targetInsideBlocks[i]
        connection.connect(targetBlock.outputConnection)
      }
    },
    updateWorkspaceWithXml () {
      const xml = Blockly.Xml.workspaceToDom(this.workspace)
      Blockly.Xml.clearWorkspaceAndLoadFromXml(xml, this.workspace)
    }
  }
}
</script>

<style scoped>

</style>
